package com.smart.common.smart.ehcache;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * ehcache工具类
 *
 * @author arnold.zhao
 * @date 2018/10/25 16:49
 */
public class EhcacheUtils {

    private static CacheManager cacheManager = null;
    private static final String config = "mybatis/ehcache.xml";

    static {
        try {
            cacheManager = CacheManager.create(EhcacheUtils.class.getClassLoader().getResourceAsStream(config));
        } catch (CacheException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 根据指定的缓存策略取出对应的Element所对应的Value
     * @Param: [cacheName, key]
     * @return: java.lang.Object
     * @Author: Arnold.zhao
     * @Date: 2018/10/29
     */
    public static Object get(String cacheName, String key) {
        Cache cacheObj = cacheManager.getCache(cacheName);
        Element element = cacheObj.get(key);
        return element == null ? null : element.getObjectValue();
    }

    /**
     * @Description: 根据指定的缓存策略存入对应的Element元素
     * @Param: [cacheName, key, value]
     * @return: void
     * @Author: Arnold.zhao
     * @Date: 2018/10/29
     */
    public static void put(String cacheName, Object key, Object value) {
        Cache cacheObj = cacheManager.getCache(cacheName);
        cacheObj.put(new Element(key, value));
    }

    /**
     * @Description: 删除指定cache的缓存元素
     * @Param: [cacheName, key]
     * @return: void
     * @Author: Arnold.zhao
     * @Date: 2018/10/29
     */
    public static void remove(String cacheName, Object key) {
        cacheManager.getCache(cacheName).remove(key);
    }

    /**
     * @Description: 删除当前cache策略的所有已存元素
     * @Param: [cacheName, key]
     * @return: void
     * @Author: Arnold.zhao
     * @Date: 2018/10/29
     */
    public static void removeAll(String cacheName) {
        cacheManager.getCache(cacheName).removeAll();
    }
}
